#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<iostream>
#include<string.h>
#include"eigen3/Eigen/Sparse"
#include"eigen3/Eigen/IterativeLinearSolvers"
using namespace Eigen;
#include<time.h>

int main()
{
    int l, nnz, i, j, dim;
    dim = 119425;
    nnz = 825737;
    char dummy;
    double val;
    clock_t start, finish;
    double time;
    start = clock();
    //创建稀疏矩阵mat
    SparseMatrix<double> mat(dim,dim);         
    mat.reserve(VectorXi::Constant(dim,30));
    
    FILE* fin = fopen("spmat2.csv", "r");
    if (fin != NULL)
	printf("稀疏矩阵数据文件打开成功！！\n");
    else{
	printf("稀疏矩阵数据文件打开失败，请检查！！\n");  return 0;
    }
    for (l = 0; l < nnz; l++){      // 开始读取数据
	fscanf(fin, "%d%c%d%c%lf", &i, &dummy, &j, &dummy, &val);
    mat.insert(i-1,j-1) = val;
    }
    mat.makeCompressed(); 
    VectorXd b(dim);
    fclose(fin);
    fin = fopen("rhs2.csv", "r");
    if (fin != NULL)
	printf("右端项数据文件打开成功！！\n");
    else{
	printf("右端项数据文件打开失败，请检查！！\n");	return 0;
    }
    for(i = 0; i < dim; i++){
	fscanf(fin, "%le", &val);
	b(i) = val;
    }
    fclose(fin);
    VectorXd x(dim);
    //利用SparesLU求解
    SparseLU<SparseMatrix<double>, COLAMDOrdering<int> >   solver;

    solver.analyzePattern(mat); 
    solver.factorize(mat); 
    x = solver.solve(b);
    VectorXd b2(dim);
    b2 = mat*x;
    VectorXd r(dim);
    r = b2 - b;     //误差向量
    double err;
    err = sqrt(r.dot(r));
    std::cout << "误差为：" << err << std::endl;
    finish = clock();
    time = (double)(finish - start) / CLOCKS_PER_SEC;
    std::cout << "时间为：" << time << std::endl;
    return 0;
}
